package com.jy.appmarket.activity;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;

import com.jy.appmarket.R;
import com.jy.appmarket.cards.InstalledAppUICard;
import com.jy.appmarket.cards.InstalledAppUICard.InstalledAppUICardOnClickListener;
import com.jy.appmarket.model.InstalledApkInfo;
import com.jy.appmarket.utils.GetInstalledPackagesCompat;
import com.jy.appmarket.view.LoadingView;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.CardArrayAdapter;
import it.gmariotti.cardslib.library.view.CardListView;

public class InstalledAppManagerActivity extends Activity implements InstalledAppUICardOnClickListener{

	private CardListView mListview;
	private CardArrayAdapter mCardsAdapter;
	private LoadingView mLoadingView;
	private View mContentLayout;
	private ArrayList<InstalledApkInfo> mInstalledApkInfoList;
	private ArrayList<Card> mCardsArray = new ArrayList<Card>();
	private int mUnFinished = Integer.MIN_VALUE;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_installed_apk_manager);

		initTitle();
		initViews();
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				loadData();
			}
		}).start();
		
		
	}
	
	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle("已安装应用");
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
	}
	
	private void setupUI(){
		if(mInstalledApkInfoList.size() == 0){
			mLoadingView.setVisibility(View.VISIBLE);
			mContentLayout.setVisibility(View.GONE);
			mLoadingView.showEmptyView("没有可卸载应用", R.drawable.apk_file_empty);
		}else {
			mCardsArray.clear();// = new ArrayList<Card>(); 
			for(int i = 0; i < mInstalledApkInfoList.size(); i++){
				InstalledAppUICard card = new InstalledAppUICard(this, mInstalledApkInfoList.get(i), this);
				mCardsArray.add(card);
			}
			if(mListview.getAdapter() == null){
				mCardsAdapter = new CardArrayAdapter(this, mCardsArray);
				mCardsAdapter.setInnerViewTypeCount(500);
				mListview.setAdapter(mCardsAdapter);
			}else{
				mCardsAdapter.notifyDataSetChanged();
			}
			
			mLoadingView.setVisibility(View.GONE);
			mContentLayout.setVisibility(View.VISIBLE);
		}
	}
	
	private void loadData(){
		
		List<PackageInfo> packages = GetInstalledPackagesCompat.getInstalledPackages(this,
				PackageManager.GET_SIGNATURES);
		PackageManager pm = this.getPackageManager();
		mInstalledApkInfoList = new ArrayList<InstalledApkInfo>();
		for (PackageInfo pi : packages) {
			
			if ((pi.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
				// system app
				
			} else {
				// user app
				if(pi.packageName.equalsIgnoreCase("com.jy.appmarket")){
					continue;
				}
				InstalledApkInfo installInfo = new InstalledApkInfo();
				
				installInfo.setPackageName(pi.packageName);
				installInfo.setApkVersionName(pi.versionName);
				installInfo.setInstallTime(pi.lastUpdateTime);
				ApplicationInfo appInfo= pi.applicationInfo;
				if(appInfo != null){
					installInfo.setApkName(appInfo.loadLabel(pm).toString());
					installInfo.setApkIcon(appInfo.loadIcon(pm));
					if(appInfo.sourceDir != null){
						File file = new File(appInfo.sourceDir);
						installInfo.setFileSize(file.length());
					}
				}
				mInstalledApkInfoList.add(installInfo);
			}
		}
		Collections.sort(mInstalledApkInfoList);
		InstalledAppManagerActivity.this.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				setupUI();
			}
		});
	}
	
	private void initViews(){
		mLoadingView = findViewById(R.id.installed_apk_manager_loading_view);
		mLoadingView.setOnClickListener(new LoadingView.OnClickListener() {

			@Override
			public void onLoadingViewClick(View view) {
				loadData();
			}
		});
		mLoadingView.showWaitView("正在查找手机安装应用");
		mLoadingView.setVisibility(View.VISIBLE);

		mContentLayout = findViewById(R.id.installed_apk_manager_content_layout);
		mContentLayout.setVisibility(View.GONE);
		mListview = findViewById(R.id.installed_apk_manager_listview);
		mListview.needToRefreshOnFooter(false);
		mListview.needToRefreshOnHeader(false);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onUninstallApp(final InstalledApkInfo apkInfo) {
		Intent intent = new Intent();
	    intent.setAction(Intent.ACTION_DELETE);
	    intent.setData(Uri.parse("package:"+apkInfo.getPackageName()));
		startActivityForResult(intent, 1000);
//		if(mUnInstallConfimDialog == null){
//			mUnInstallConfimDialog = new TextDialog(this);
//		}
//		mUnInstallConfimDialog.showTitle("卸载应用").setContent("确定要卸载"+apkInfo.getApkName()+"吗？")
//		.showButton1("关闭", new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				mUnInstallConfimDialog.cancel();
//			}
//		}).showButton2("确定", new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				Intent intent = new Intent();
//			    intent.setAction(Intent.ACTION_DELETE);
//			    intent.setData(Uri.parse("package:"+apkInfo.getPackageName()));
//				startActivityForResult(intent, 1000);
//				mUnInstallConfimDialog.cancel();
//			}
//		}).show();
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode == 1000){
			loadData();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
